<?php
/**
 * 我的红包
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */

use Shopnc\Tpl;
use Shopnc\Log;

defined('InShopNC') or exit('Access Invalid!');

class member_redpacketControl extends mobileMemberControl {
    private $redpacket_state_arr;

    public function __construct() {
        parent::__construct();
        //判断系统是否开启红包功能
        if (C('redpacket_allow') != 1){
            output_error('系统未开启红包功能');
        }
        $model_redpacket = Model('redpacket');
        $this->redpacket_state_arr = $model_redpacket->getRedpacketState();
    }
    /*
     * 我的红包列表
     */
    public function redpacket_listOp(){
        $param = $_POST;
        $model_redpacket = Model('redpacket');
        //更新红包过期状态
        $model_redpacket->updateRedpacketExpire($this->member_info['member_id']);
        //查询红包
        $where = array();
        $where['rpacket_owner_id'] = $this->member_info['member_id'];
        $rp_state_select = trim($param['rp_state']);
        if ($rp_state_select){
            $where['rpacket_state'] = $this->redpacket_state_arr[$rp_state_select]['sign'];
        }
        $redpacket_list = $model_redpacket->getRedpacketList($where, '*', 0, $this->page, 'rpacket_state asc,rpacket_id desc');
        $page_count = $model_redpacket->gettotalpage();
        output_data(array('redpacket_list' => $redpacket_list), mobile_page($page_count));
    }
    /**
     * 卡密领取红包
     */
    public function rp_pwexOp(){
        $param = $_POST;
        $pwd_code = trim($param["pwd_code"]);
        if (!$pwd_code) {
            output_error('请输入红包卡密');
        }
        if (!Model('apiseccode')->checkApiSeccode($param["codekey"],$param['captcha'])) {
            output_error('验证码错误');
        }
        //查询红包
        $model_redpacket = Model('redpacket');
        $redpacket_info = $model_redpacket->getRedpacketInfo(array('rpacket_pwd'=>md5($pwd_code)));
        if(!$redpacket_info){
            output_error('红包卡密错误');
        }
        if($redpacket_info['rpacket_owner_id'] > 0){
            output_error('该红包卡密已被使用');
        }
        $where = array();
        $where['rpacket_id'] = $redpacket_info['rpacket_id'];
        $update_arr = array();
        $update_arr['rpacket_owner_id'] = $this->member_info['member_id'];
        $update_arr['rpacket_owner_name'] = $this->member_info['member_name'];
        $update_arr['rpacket_active_date'] = time();
        $result = $model_redpacket->editRedpacket($where, $update_arr, $this->member_info['member_id']);
        if($result){
            //更新红包模板
            $update_arr = array();
            $update_arr['rpacket_t_giveout'] = array('exp','rpacket_t_giveout+1');
            $model_redpacket->editRptTemplate(array('rpacket_t_id'=>$redpacket_info['rpacket_t_id']),$update_arr);
            output_data('1');
        } else {
            output_error('红包领取失败');
        }
    }

    /**
     * 是否具有领取新人红包的权限
     * @return bool  --  true - 具有 / false -不具备
     */
    public function newbie_redpacket_jurisdictionOp()
    {
        $result = false;
        $member_id = (int)$this->member_info['member_id'];
        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        //查询是否具有权限
        $model_redpacket = Model('redpacket');
        $redpacket_jurisdiction = $model_redpacket->newbieRedpacketJurisdiction($member_id);
        if (isset($redpacket_jurisdiction['state']) && ($redpacket_jurisdiction['state'] === true)) $result = true;
        output_data(['redpacket_jurisdiction' => $result], $redpacket_jurisdiction);
    }

    /**
     * 得到新人红包
     * @return json
     */
    public function get_newbie_redpacketOp()
    {
        $member_id = (int)$this->member_info['member_id'];
        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        //红包模板id
        $rpacket_t_id = isset($_POST['rpacket_t_id']) ? (int)$_POST['rpacket_t_id'] : 0;
        $model_redpacket = Model('redpacket');
        //验证是否可领取红包
        $data = $model_redpacket->getCanChangeTemplateInfo($rpacket_t_id, $member_id);
        if ($data['state'] !== true){
             output_error($data['msg']);
        }
        //生成红包记录
        try {
            $model_redpacket->beginTransaction();
            //添加红包信息
            $data = $model_redpacket->exchangeRedpacket($data['info'], $member_id, $this->member_info['member_name']);
            if ($data['state'] !== true ) {
                throw new Exception($data['msg']);
            }
            //发送红包领取成功服务通知
            Logic('applet_notice')->appletRedpacketFetchSuccess($data['rpacket_id']);

            $model_redpacket->commit();
        } catch (Exception $e) {
            $model_redpacket->rollback();
            output_error('领取失败');
            // output_error($e->getMessage());
        }
        output_data('领取成功');
    }

    /**
     * 领取免费红包
     */
    public function get_free_redpacketOp()
    {
        $member_id = (int)$this->member_info['member_id'];
        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        $parameter = $_POST;    //提交参数

        //红包模板id
        $rpacket_t_id = isset($parameter['rpacket_t_id']) ? (int)$parameter['rpacket_t_id'] : 0;
        $model_redpacket = Model('redpacket');

        //验证是否可领取红包
        $data = $model_redpacket->getCanChangeTemplateInfo($rpacket_t_id, $member_id);
        if ($data['state'] == false){
            output_error($data['msg']);
        }

        $rpacket_t_gettype = isset($data['info']['rpacket_t_gettype']) ? (int)$data['info']['rpacket_t_gettype'] : '';
        if ($rpacket_t_gettype === '') {
            output_error('错误的红包数据');
        }
        //验证领取方式是否是免费领取
        if ($rpacket_t_gettype !== $model_redpacket::RPACKET_GET_FREE) {
            output_error('该红包领取方式，不为免费');
        }

        try {
            $model_redpacket->beginTransaction();
            //添加红包信息
            $data = $model_redpacket->exchangeRedpacket($data['info'], $member_id);
            if ($data['state'] == false) {
                throw new Exception($data['msg']);
            }
            $model_redpacket->commit();
        } catch (Exception $e) {
            $model_redpacket->rollback();
            output_error($e->getMessage());
        }
        
        output_data('领取成功');
        
    }


    /**
     * 红包分享成功回调 -- 获得红包限制由分享次数决定
     * @return json
     */
    public function share_redpacket_callback_shareOp()
    {
        $member_id = (int)$this->member_info['member_id'];
        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        //传递参数
        $parameter = $_POST;
        $if_invalid = false;  //是否是点击他人分享链接
        $redpacket_share_person = isset($parameter['redpacket_share_person']) ? $parameter['redpacket_share_person'] : '';  //红包分享人
        $redpacket_share_secretkey = isset($parameter['redpacket_share_secretkey']) ? $parameter['redpacket_share_secretkey'] : '';    //红包分享比对密钥
        //红包模板id
        $rpacket_t_id = isset($parameter['rpacket_t_id']) ? (int)$parameter['rpacket_t_id'] : 0;

        $model_redpacket = Model('redpacket');
        //分享加密密钥 - 防止无效调用
        if ($redpacket_share_person && $redpacket_share_secretkey) {
            $decrypt_parameter = $model_redpacket->decryptParameter($redpacket_share_person, $redpacket_share_secretkey, $rpacket_t_id);
            $redpacket_share_person =  (is_array($decrypt_parameter) && isset($decrypt_parameter['member_id'])) ? (int)$decrypt_parameter['member_id'] : 0;
            if ($redpacket_share_person && ($redpacket_share_person === $member_id)) $if_invalid = true;
        }

        //是否无效调用
        if ($if_invalid !== true) {
            output_error('无效调用');
        }

        //将红包分享次数加一
        $model_redpacket_share = Model('redpacket_share');
        $share_number_state = $model_redpacket_share->addShareNumber($member_id, $rpacket_t_id);
        if ($share_number_state === false) {
            output_error('创建分享数据失败');
        }

        //验证是否可领取红包
        $data = $model_redpacket->getCanChangeTemplateInfo($rpacket_t_id, $member_id, $redpacket_share_secretkey);
        /*用秘钥判断该红包是否已经获取过，防止用户重复获取该红包*/
        $data['info']['redpacket_share_secretkey'] = $redpacket_share_secretkey;
        if ($data['state'] !== true) {
             output_error($data['msg']);
        
        } else {  //可以领取红包
            try {
                $model_redpacket->beginTransaction();
                //添加红包信息
                $data = $model_redpacket->exchangeRedpacket($data['info'], $member_id, $this->member_info['member_name']);
                if ($data['state'] !== true ) {
                    throw new Exception($data['msg']);
                }
                $model_redpacket->commit();
            } catch (Exception $e) {
                $model_redpacket->rollback();
                output_error('分享红包发送失败');
                // output_error($e->getMessage());
            }

        }
        output_data('分享红包发送成功');
    }


    /**
     * 红包分享成功回调 -- 获得红包限制由引流人数决定
     * @return json
     */
    public function share_redpacket_callback_drainageOp()
    {
        output_error('接口未开放');
        $member_id = (int)$this->member_info['member_id'];
        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        //传递参数
        $parameter = $_GET;
        //红包模板id
        $rpacket_t_id = isset($parameter['rpacket_t_id']) ? (int)$parameter['rpacket_t_id'] : 0;
        //检查是否生成分享记录
        $model_redpacket_share = Model('redpacket_share');
        $map = array(
            'member_id' => $member_id,
            'rpacket_t_id' => $rpacket_t_id
        );
        $if_create = $model_redpacket_share->ifExist($map);
        if ($if_create) output_data('分享成功');  //已添加必要数据，直接返回成功

        $model_redpacket = Model('redpacket');
        //验证是否可领取红包
        $data = $model_redpacket->getCanChangeTemplateInfo($rpacket_t_id, $member_id);
        if ($data['state'] !== true) {
             output_error($data['msg']);
        
        } else {  //可以领取红包
            try {
                $model_redpacket->beginTransaction();
                //添加红包信息
                $data = $model_redpacket->exchangeRedpacket($data['info'], $member_id, $this->member_info['member_name']);
                if ($data['state'] !== true ) {
                    throw new Exception($data['msg']);
                }
                //添加分享记录
                $add_data = array(
                    'rpacket_t_id'     => $rpacket_t_id,
                    'member_id'        => $member_id,
                    'parent_member_id' => 0,
                );
                $add_state = $model_redpacket_share->addData($add_data);
                if (!$add_state) {
                    throw new Exception('添加分享记录失败');
                }
                $model_redpacket->commit();
            } catch (Exception $e) {
                $model_redpacket->rollback();
                output_error('分享红包发送失败');
                // output_error($e->getMessage());
            }

        }
        output_data('分享红包发送成功');
    }

    /**
     * 得到分享参数
     * @return json
     */
    public function get_share_parameterOp()
    {
        $member_id = (int)$this->member_info['member_id'];
        if (empty($member_id)) output_error('请登录', array('login' => '0'));
        //红包模板id
        $rpacket_t_id = isset($_GET['rpacket_t_id']) ? (int)$_GET['rpacket_t_id'] : 0;
        $model_redpacket = Model('redpacket');
        $map = array(
            'rpacket_t_id' => $rpacket_t_id,
            'rpacket_t_type' => $model_redpacket::RPACKET_TYPE_SHARE,
            'rpacket_t_start_date' => array('elt', TIMESTAMP),
            'rpacket_t_end_date' => array('egt', TIMESTAMP),
            'rpacket_t_state' => $model_redpacket::RPACKET_STATE_USABLE
        );
        $field = 'rpacket_t_id,rpacket_t_type,rpacket_t_price,rpacket_t_price_type';
        $redpacket_info = $model_redpacket->getRptTemplateInfo($map, $field);
        if (empty($redpacket_info)) {
            output_error('不存在该有效的分享红包');
        }

        $encrypt_parameter = $model_redpacket->encryptParameter($member_id, $rpacket_t_id);
        $encrypt_parameter += array('rpacket_t_price' => $redpacket_info['rpacket_t_price']);
        output_data($encrypt_parameter);
    }

}
